﻿// 加载Express模块
const express = require("express");
const md5 = require("md5");
// 加载MySQL模块
const mysql = require("mysql");

// 加载bodyParser模块
const bodyParser = require("body-parser");

var request = require("request");

// 创建MySQL连接池
const pool = mysql.createPool({
  host: "127.0.0.1", //MySQL服务器地址
  port: 3306, //MySQL服务器端口号
  user: "root", //数据库用户的用户名
  password: "", //数据库用户密码
  database: "yuedu", //数据库名称
  connectionLimit: 20, //最大连接数
  charset: "utf8", //数据库服务器的编码方式
});

// 创建服务器对象
const server = express();
//配置multer中间件（用于存储上传的文件）
const multer = require("multer");
server.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
// 加载CORS模块
const cors = require("cors");
// 使用CORS中间件
server.use(
  cors({
    origin: "*",
  })
);
server.post("/register", (req, res) => {
  let name = req.body.name;
  let phone = req.body.phone;
  let email = req.body.email;
  let pwd = req.body.pwd;
  //console.log(name, phone, email, pwd);
  if (!pwd || !name || !phone || !email) {
    res.send({ message: "某个注册字段为空！", code: 201 });
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    res.send({ message: "手机号格式错误！", code: 202 });
    return;
  }
  if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)) {
    res.send({ message: "邮箱格式错误！", code: 203 });
    return;
  }
  if (!/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{8,16}$/.test(pwd)) {
    res.send({ message: "密码不合规！", code: 204 });
  }
  // 判断用户名是否被占用
  pool.query("SELECT u_id FROM yuedu_members WHERE u_name=?", [name], (error, result) => {
    if (error) throw error;
    if (result.length == 0) {
      // 判断手机号是否已注册
      pool.query("SELECT u_id FROM yuedu_members WHERE u_phone=?", [phone], (error, result) => {
        if (error) throw error;
       // console.log(result);
        if (result.length == 0) {
          // 判断邮箱是否已注册
          pool.query("SELECT u_id FROM yuedu_members WHERE u_email=?", [email], (error, result) => {
            if (error) throw error;
           // console.log(result);
            if (result.length == 0) {
              // 将用户相关信息插入到数据表
              let sql = "INSERT yuedu_members(u_name,u_pwd,u_email,u_phone) VALUES(?,?,?,?)";
              pool.query(sql, [name, md5(pwd), email, phone], (error, result) => {
               // console.log(email);
                if (error) throw error;
                res.send({ message: "ok", code: 200 });
              });
            } else {
              res.send({ message: "该邮箱已经注册过！", code: 207 });
            }
          });
        } else {
          res.send({ message: "该手机已经注册过！", code: 206 });
        }
      });
    } else {
      res.send({ message: "该用户名已被占用！", code: 205 });
    }
  });
});
server.post("/applogin", (req, res) => {
  let account = req.body.name;
  let pwd = req.body.pwd;
  if (!account || !pwd) {
    res.send({ message: "用户名或密码为空！", code: 201 });
  }
  // 手机号及邮箱满足其一，密码正确则允许登录
  let sql = "SELECT * FROM yuedu_members WHERE u_pwd=? and (u_phone=? or u_email=?)";
  pool.query(sql, [md5(pwd), account, account], (error, result) => {
    if (error) throw error;
    if (result.length == 0) {
      res.send({ message: "login failed", code: 201 });
    } else {
      res.send({ message: "登录成功", code: 200, result: result });
    }
  });
});
server.post("/login", (req, res) => {
  let openid = req.body.openid;
  let name = req.body.name;
  let face = req.body.face;
  pool.query("SELECT  *  FROM  yuedu_members where u_openid=?", [openid], (err, data) => {
    if (err) throw err;
    if (data.length > 0) {
      res.send({ message: "ok", code: 200, data });
    } else {
      pool.query("INSERT yuedu_members(u_openid,u_name,u_face) VALUES(?,?,?)", [openid, name, face], (err, data) => {
        if (err) throw err;
        pool.query("SELECT  *  FROM  yuedu_members where u_openid=?", [openid], (err, data) => {
          res.send({ message: "ok", code: 200, data });
        });
      });
    }
  });
});
server.get("/getcode", (req, res) => {
  var code = req.query.code;
  request(
    `https://api.weixin.qq.com/sns/jscode2session?appid=wx70b0f987d2df7aec&secret=98e1105263bd82edd9ca87ac9920137e&js_code=${code}&grant_type=authorization_code`,
    function (err, response, body) {
      //err 当前接口请求错误信息
      //response 一般使用statusCode来获取接口的http的执行状态
      //body 当前接口response返回的具体数据 返回的是一个jsonString类型的数据
      //需要通过JSON.parse(body)来转换
      if (!err && response.statusCode == 200) {
        //todoJSON.parse(body)
        var data = JSON.parse(body);
      }
      res.send({ message: "ok", code: 200, data });
    }
  );
});
server.get("/category", (req, res) => {
  // SQL语句以获取文章分类表的数据
  let sql = "SELECT  *  FROM  yuedu_categories";
  // 执行SQL语句
  pool.query(sql, (error, data) => {
    if (error) throw error;
    res.send({ message: "ok", code: 200, data: data });
  });
});
server.get("/getList", (req, res) => {
  let cate = req.query.cate;
  let page = req.query.page;
  // 存储每页显示的记录数
  let pagesize = 10;
  // 通过公式来计算从第几条记录开始返回
  let offset = (page - 1) * pagesize;
  if (cate == 0) {
    pool.query("SELECT  *  FROM  yuedu_articles LIMIT ?,?", [offset, pagesize], (error, data) => {
      if (error) throw error;
      res.send({ message: "ok", code: 200, data: data });
    });
  } else {
    pool.query("SELECT  *  FROM  yuedu_articles WHERE art_cate=? LIMIT ?,?", [cate, offset, pagesize], (error, data) => {
      if (error) throw error;
      res.send({ message: "ok", code: 200, data: data });
    });
  }
});

//图片上传设置
obj = multer.diskStorage({
  //磁盘存储
  destination: function (req, file, cb) {
    //指定目录
    cb(null, "upload");
  },
  filename: function (req, file, cb) {
    // 指定文件名
    let name = file.originalname;
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf("."));
    cb(null, uuid.v4() + ext); //uuid.v4 生成随机值的模块
  },
});
const uploadTools = multer({
  storage: obj, //定义文件的存储规则(怎么存？保存在哪？文件名？)
});
const uuid = require("uuid");
// const { default: md5 } = require("uuid/dist/md5");
// 静态资源托管upload目录
server.use(express.static("upload"));
//接收请求
server.post("/uploadimg", uploadTools.array("file"), (req, res) => {
  console.log(req.files);
  // 整理图片访问地址，返回给客户端
  let urls = [];
  req.files.forEach(i => {
    //forEach((value)=>{})
    urls.push(i.filename);
  });
  res.send({
    msg: "ok",
    urls: urls,
  });
});
server.post("/uploadface", uploadTools.array("file"), (req, res) => {
  //console.log(req.files);
 // console.log(req.body);
  let uid= req.body.uid;
  let imgurl = "http://1.14.30.101:8085/" + req.files[0].filename;
  pool.query("UPDATE yuedu_members SET u_face=? WHERE u_id=?", [imgurl, uid], (error, result) => {
    if (error) throw error;
   // console.log(imgurl, uid);
   // console.log(result.changedRows);
    if (result.changedRows != 0) {
      res.send({
        msg: "ok",
        imgurl: imgurl,
        code: 200,
      });
    } else {
      res.send({
        msg: "err",
        code: 201,
      });
    }
  });
});
server.post("/addActicle", (req, res) => {
  let title = req.body.title;
  let content = req.body.content;
  let uid = req.body.uid;
  let cate = req.body.cate;
  pool.query("INSERT yuedu_articles(art_cate,art_title,art_uid,art_content) VALUES(?,?,?,?)", [cate, title, uid, content], (err, data) => {
    if (err) throw err;
    res.send({ message: "ok", code: 200 });
  });
});
server.post("/userinfo", (req, res) => {
  let uid = req.body.uid;
  pool.query("SELECT COUNT(art_uid) AS count FROM yuedu_articles WHERE art_uid=?", [uid], (err, data) => {
    if (err) throw err;
    let artCount = data[0].count;
    pool.query("SELECT  *  FROM  yuedu_members WHERE u_id=?", [uid], (err, data) => {
      if (err) throw err;
      res.send({
        message: "ok",
        code: 200,
        data: {
          u_name: data[0].u_name,
          u_integral: data[0].u_integral,
          u_remainder: data[0].u_remainder,
          artCount: artCount,
        },
      });
    });
  });
});
server.post("/arts", (req, res) => {
  let page = req.query.page;
  let uid = req.body.uid;
  // 存储每页显示的记录数
  let pagesize = 5;
  // 通过公式来计算从第几条记录开始返回
  let offset = (page - 1) * pagesize;
  pool.query("SELECT  *  FROM  yuedu_articles WHERE art_uid=? LIMIT ?,?", [uid, offset, pagesize], (err, data) => {
    if (err) throw err;
    if (data.length != 0) {
      res.send({ message: "ok", code: 200, data });
    } else {
      res.send({ message: "empty", code: 201, data });
    }
  });
});
server.post("/removeArt", (req, res) => {
  let uid = req.body.uid;
  let artid = req.body.artId;
  pool.query("delete FROM  yuedu_articles WHERE art_uid=? and art_id=?", [uid, artid], (err, data) => {
    if (err) throw err;
    res.send({ message: "ok", code: 200 });
  });
});
server.get("/infoWithUser", (req, res) => {
  let artid = req.query.artid;
  console.log(artid);
  pool.query("SELECT  *  FROM  yuedu_articles WHERE art_id=?", [artid], (err, data) => {
    if (err) throw err;
    let uid = data[0].art_uid;
    let content = data[0].art_content;
    let title = data[0].art_title;
    pool.query("SELECT  *  FROM  yuedu_members WHERE u_id=?", [uid], (err, data) => {
      if (err) throw err;
      res.send({
        message: "ok",
        code: 200,
        data: {
          u_face: data[0].u_face,
          u_name: data[0].u_name,
          art_title: title,
          art_content: content,
        },
      });
    });
  });
});
// 指定服务器对象监听的端口号
server.listen(8085, () => {
  console.log("server is running...listen 8085");
});
